<?php

namespace Kollway\CodeGenerator\Commands;

use Kollway\CodeGenerator\Utils\DBUtils;

use Kollway\CodeGenerator\Generators\ControllerGenerator;
use Kollway\CodeGenerator\Generators\FormViewGenerator;
use Kollway\CodeGenerator\Generators\ListViewGenerator;
use Kollway\CodeGenerator\Generators\ModelGenerator;
use Kollway\CodeGenerator\Services\YamlService;

use Illuminate\Support\Str;

class CodeGeneratorCommand extends BaseCommand
{
    public $signature = "cg {--file=config.yml}";

    public $description = "根据配置文件生成与某个表相关的 Controller、Model、list、form 文件";

    /** @throws \Throwable */
    public function handle()
    {
        if (!is_dir(base_path('code-gen'))) {
            mkdir(base_path('code-gen'));
        }

        $this->generateFieldKeywordsToFile();

        // 需要解析的文件
        $file = $this->option('file');
        $yaml_config = base_path('code-gen/' . $file);

        if (!is_file($yaml_config)) {
            $this->info('文件不存在: ' . $yaml_config);
            return;
        }

        $configs = yaml_parse_file($yaml_config);
        if (!$configs) {
            $this->info('yml文件解析失败: ' . $yaml_config);
            return;
        }
        // 检查 yaml 配置(不完善)
        if (is_string($error = (new YamlService())->checkSyntax($configs))) {
            $this->info($error);
            return;
        }

        foreach ($configs as $table => $options) {
            $camel_name = ucfirst(Str::camel($table));

            $controller_generator = new ControllerGenerator($table, $options);
            $controller_generator->generateControllerString();
            $controller_generator->writeToFile();

            $model_generator = new ModelGenerator($table, $options);
            $model_generator->generateModelString();
            $model_generator->writeToFile();

            $form_type = $options['form_type'] ?? '';
            if ($form_type != 'dialog') {
                // 对话框类型表单不生成独立的表单视图文件(在 list 视图中使用 modal 弹窗)
                $form_view_generator = new FormViewGenerator($table, $options);
                $form_view_generator->generateFormViewString();
                $form_view_generator->writeToFile();
            }

            $list_view_generator = new ListViewGenerator($table, $options);
            $list_view_generator->generateListViewString();
            $list_view_generator->writeToFile();

            // 添加隐式控制器路由
            $route_file = fopen(app_path('Http/routes.php'), 'a');
            $rout_string = "\nRoute::controller('{$camel_name}', 'Admin\\{$camel_name}Controller');";
            if (strpos(file_get_contents(app_path('Http/routes.php')), $rout_string) === false) {
                fwrite($route_file, "\n//Route::controller('{$camel_name}', 'Admin\\{$camel_name}Controller');");
            }
            fclose($route_file);
        }
    }

    // 生成字段名列表到文件(用于 idea 插件索引)
    private function generateFieldKeywordsToFile()
    {
        $fields = DBUtils::getAllTablesAndFields();

        $prefix = \DB::getTablePrefix();

        $file = fopen(base_path('code-gen/fields.txt'), 'w+');
        foreach ($fields as $key => $field) {
            if (strpos($field, $prefix) !== false) {
                $field = str_replace($prefix, '', $field);
            }

            if ($key + 1 != count($fields)) {
                fwrite($file, $field . "\n");
            } else {
                fwrite($file, $field);
            }
        }
        fclose($file);
    }
}